package com.dtanner.books;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class HttpLib {

	private HttpClient http;
	private String response;

	private final static Logger logger = Logger.getLogger(HttpLib.class);

	public HttpLib() {
		http = new HttpClient();
	}

	public String getRequest(String url, NameValuePair query) {
		try {
            GetMethod getRequest = new GetMethod(url);
            getRequest.setQueryString(query.getName() + "=" + query.getValue());
            httpRequest(getRequest);
        } catch (UnsupportedEncodingException e) {
            logger.fatal(StackToString.toString(e));
        } catch (IOException e) {
            logger.fatal(StackToString.toString(e));
        }
		String temp = response;
        response = null;
		return temp;
	}

	public void httpRequest(HttpMethod method) throws IOException,
			HttpException {
		response = null;
		try {
			int statusCode = http.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				logger.debug("POST method failed: " + method.getStatusLine());
				response = getResponseBodyFromStream(method
						.getResponseBodyAsStream());
			} else {
				logger.debug("POST method succeeded: " + method.getStatusLine());
				response = getResponseBodyFromStream(method
						.getResponseBodyAsStream());
			}
			method.releaseConnection();
		} catch (URIException e) {
			logger.fatal(method.getQueryString());
			throw new URIException("Failed");
		}

	}

	public static String getResponseBodyFromStream(InputStream is) {
		String str = "";
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[128];
			int size = 0;
			while ((size = is.read(buffer)) > 0) {
				baos.write(buffer, 0, size);
			}
			str = new String(baos.toByteArray());
		} catch (IOException ioe) {
		}
		return str;
	}

}
